//
//  DatabaseStoreHelper.m
//  CedarFinancePH
//
//  Created by 门超 on 2018/9/2.
//  Copyright © 2018年 cedarhd. All rights reserved.
//

#import "DatabaseStoreHelper.h"
#import "YTKKeyValueStore.h"

static NSString * kDataBaseName = @"AppConfigueDB.sqlite";
static NSString * kTableName = @"AppConfigue";


@interface DatabaseStoreHelper()

@property (nonatomic,strong) YTKKeyValueStore *store;
@property (nonatomic,copy) NSString *databaseName;
@property (nonatomic,copy) NSString *dbTableName;

@end

@implementation DatabaseStoreHelper

+ (instancetype)shareInstance{
    static DatabaseStoreHelper *dataBaseStore = nil;
    static dispatch_once_t predicate;
    dispatch_once(&predicate, ^{
         dataBaseStore = [[DatabaseStoreHelper alloc] initWithDatabaseName:kDataBaseName tableName:kTableName];
    });
    return dataBaseStore;
}

- (instancetype)initWithDatabaseName:(NSString *)dbName tableName:(NSString *)tableName {
    self = [super init];
    if (self) {
        self.databaseName = dbName;
        self.dbTableName = tableName;
        self.store = [[YTKKeyValueStore alloc] initDBWithName:self.databaseName];
        [self.store createTableWithName:self.dbTableName];
    }
    return self;
}

- (void)saveObject:(id)object className:(NSString *)className{
    [self json_putObject:object withId:className intoTable:self.dbTableName];
}

- (id)getObjectWithClassName:(NSString *)className{
    return [self object_getObjectById:className fromTable:self.dbTableName objectClass:NSClassFromString(className)];
}

/** 清除数据库 */
- (void)deleteObjectByClassName:(NSString *)className {
    [self.store deleteObjectById:className fromTable:self.dbTableName];
}

- (void)json_putObject:(id)object withId:(NSString *)objectId intoTable:(NSString *)tableName{
    [self.store putObject:[object mj_keyValues] withId:objectId intoTable:tableName];
}

- (id)object_getObjectById:(NSString *)objectId fromTable:(NSString *)tableName objectClass:(Class)objectClass{
    NSDictionary * dic = [_store getObjectById:objectId fromTable:tableName];
    return [objectClass mj_objectWithKeyValues:dic];
}

@end
